<script setup>
import _ from 'lodash';
import NodeDataValue from "./node-data-value.vue";
import {onMounted, ref, watch} from "vue";

const modelValue = defineModel()

const props = defineProps({
  placeholder: {
    type: String,
    default: "选择/自定义 绑定数据"
  },
  value: String,
  disabled: false
})

const nvValue = ref("")
const visible = ref(false)
const isFocus = ref(false)
const refreshKey = ref('')

onMounted(() => {
  nvValue.value = modelValue.value
})

watch(() => modelValue.value, (newVal) => {
  nvValue.value = newVal
})

watch(() => nvValue.value, (newVal) => {
  modelValue.value = newVal
})

const handleTrigger = () => {
  if (props.disabled) return;
  visible.value = !visible.value;
}

const closeOver = () => {
  visible.value = false;
}

const handleSelect = (val) => {

}

const refreshFormatter = () => {
  let val = nvValue.value;
  nvValue.value = '';

  setTimeout(() => {
    nvValue.value = val;
  }, 0)
}

const handleFocus = () => {
  isFocus.value = true;
  // refreshKey.value = $utils.getNanoid()
  refreshFormatter()
}

const handleBlur = () => {
  isFocus.value = false;
  // refreshKey.value = $utils.getNanoid()
  refreshFormatter()
}

const formatter = (val) => {
  if(isFocus.value) {
    return val
  } else {
    return val.replace(/^iVar:/, '')
  }
}

const getNvTypeTheme = (nvValue) => {
  if(_.startsWith(nvValue, 'var:')) {
    return 'warning'
  } else if (_.startsWith(nvValue, 'scope:')) {
    return 'success'
  } else {
    return 'primary'
  }
}

const getNvTypeLabel = (nvValue) => {
  if(_.startsWith(nvValue, 'var:')) {
    return '页面'
  } else if (_.startsWith(nvValue, 'scope:')) {
    return '作用域'
  } else {
    return '模块'
  }
}
</script>

<template>
  <el-popover
    v-model:visible="visible"
    placement="left"
    title="数据绑定"
    width="360"
    trigger="manual"
    popper-class="node-view-data node-view-data-popover"
    v-click-outside="closeOver"
  >
    <template #reference>
      <div
        class="node-view-data-row"
        @click="handleTrigger">
        <el-input
          :key="refreshKey"
          v-model="nvValue"
          :placeholder="placeholder"
          :formatter="formatter"
          :disabled="disabled"
          @focus="handleFocus"
          @blur="handleBlur"
        >
          <template #prefix v-if="!isFocus">
            <el-tag
              :type="getNvTypeTheme(nvValue)"
              style="margin-left: -6px;"
            >{{ getNvTypeLabel(nvValue) }}</el-tag>
          </template>
        </el-input>
      </div>
    </template>

    <NodeDataValue
      v-model="nvValue"
      v-if="visible"
      v-bind="$attrs"
      @select="handleSelect"
    />
  </el-popover>
</template>
